package es.esi.gemde.modeltransformator.acceleoengine;

import java.io.File;

import org.eclipse.acceleo.model.mtl.Module;
import org.eclipse.acceleo.model.mtl.ModuleElement;
import org.eclipse.acceleo.model.mtl.Template;
import org.eclipse.acceleo.parser.AcceleoSourceBuffer;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

public class AcceleoEngineActivator implements BundleActivator {

	private static BundleContext context;
	static final String PLUGIN_ID = "es.esi.gemde.modeltransformator.acceleoengine";

	static BundleContext getContext() {
		return context;
	}

	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext bundleContext) throws Exception {
		AcceleoEngineActivator.context = bundleContext;
	}

	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext bundleContext) throws Exception {
		AcceleoEngineActivator.context = null;
	}
	
	/**
	 * This method creates the directory of the tool is needed. This directory will be used for storing temporal data.
	 */
	public static File createDir () {
		// We store the file to a temporary folder in the workspace metadata region
		IPath wsPath = ResourcesPlugin.getWorkspace().getRoot().getLocation();
		
		// Create the directories if needed
		File dir = wsPath.append(".metadata/.plugins").toFile();
		if (!dir.exists() || !dir.isDirectory()) {
			dir.mkdir();
		}
		
		dir = wsPath.append(".metadata/.plugins/" + PLUGIN_ID).toFile();
		if (!dir.exists() || !dir.isDirectory()) {
			dir.mkdir();
		}
		
		return dir;
	}
	
	/**
	 * This method empties the temporal directory of the tool. 
	 * It is called after an analysis operation has been completed.
	 */
	public static void cleanupDir () {
		// We store the file to a temporary folder in the workspace metadata region
		IPath wsPath = ResourcesPlugin.getWorkspace().getRoot().getLocation();
		
		// Go to the temporal MAST tool directory
		File dir = wsPath.append(".metadata/.plugins/" + PLUGIN_ID).toFile();
		if (dir.exists() && dir.isDirectory()) {
			for (File f : dir.listFiles()) {
				f.delete();
			}
		}
	}
	
	public static Template getMainTemplate(AcceleoSourceBuffer sb) {
		Template ret = null;
		int mainCount = 0;
		Module mdl = sb.getAST();
		for (ModuleElement me : mdl.getOwnedModuleElement()) {
			if (me instanceof Template && ((Template)me).isMain()) {
				ret = (Template)me;
				mainCount++;
			}
		}
		
		if (mainCount == 1) {
			return ret;
		}
		
		return null;
	}

}
